package com.ruoyi.web.controller.publish;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.publish.domain.IdIdentsample;
import com.ruoyi.publish.mapper.IdIdentsampleMapper;
import com.ruoyi.publish.service.IIdIdentsampleService;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysUserService;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.publish.domain.IdAcceptRegister;
import com.ruoyi.publish.service.IIdAcceptRegisterService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 鉴定受理登记Controller
 *
 * @author confusefox
 * @date 2020-11-04
 */
@Controller
@RequestMapping("/publish/register")
public class IdAcceptRegisterController extends BaseController {
    private String prefix = "publish/register";

    private String[] categoryAll = {"图书", "期刊", "报纸", "音像制品", "电子出版物", "网络出版物"};

    @Autowired
    private IIdAcceptRegisterService idAcceptRegisterService;

    @Autowired
    private IIdIdentsampleService idIdentsampleService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IdIdentsampleMapper idIdentsampleMapper;

    //    @RequiresPermissions("publish:register:view")
    @GetMapping()
    public String register(ModelMap mmap) {
        //传入当前人 lginname 进行鉴定队长 筛选显示审核按键
        String userId = String.valueOf(ShiroUtils.getUserId());
        List<SysUserRole> roles = iSysUserService.selectUserRoleByUserId(ShiroUtils.getUserId());


        String yearNum = DateUtils.dateTimeNow("YYYY");
//        SimpleDateFormat format = new SimpleDateFormat("yyyy");
//        Calendar c = Calendar.getInstance();
//        c.setTime(new Date());
//        c.add(Calendar.YEAR, -1);
//        Date y = c.getTime();
//        String yearNum = format.format(y);

        int grouper = 0;
        if (roles != null && roles.size() != 0) {
            for (int i = 0; i < roles.size(); i++) {
                if ("3".equals(String.valueOf(roles.get(i).getRoleId()))) {
                    grouper = 1;
                    break;
                }
            }
        }

        mmap.put("userId", userId);
        mmap.put("grouper", grouper);
        mmap.put("year", yearNum);

        return prefix + "/register";
    }

    /**
     * 查询鉴定受理登记列表
     */
//    @RequiresPermissions("publish:register:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(IdAcceptRegister idAcceptRegister) {
        startPage();
        //更新以前已鉴定样本状态
        idIdentsampleMapper.updateStatus();
        List<IdAcceptRegister> listAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterList(idAcceptRegister);
        /*for (IdAcceptRegister acceptRegister : listAcceptRegister) {
            List<IdIdentsample> idIdentsamples = idIdentsampleMapper.selectIdIdentsampleByRegisterId(acceptRegister.getId());
            boolean isStatus = true;
            for (IdIdentsample idIdentsample : idIdentsamples) {
                String status = idIdentsample.getStatus();
                if ("1".equals(status) || "0".equals(status) || StringUtils.isEmpty(status)) {
                    isStatus = false;
                    break;
                }
            }
            if (isStatus && acceptRegister.getId() != null) {
                IdAcceptRegister register = idAcceptRegisterService.selectIdAcceptRegisterById(acceptRegister.getId());
                register.setAuditStatus("6");
                idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister);
            }
        }*/

        return getDataTable(listAcceptRegister);
    }

    /**
     * 根据ID鉴定受理登记
     */
//    @RequiresPermissions("publish:register:findById")
    @PostMapping("/findById/{registerId}")
    @ResponseBody
    public IdAcceptRegister findById(@PathVariable("registerId") Long registerId) {
        IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(registerId);
        return idAcceptRegister;
    }

    /**
     * 导出鉴定受理登记列表
     */
//    @RequiresPermissions("publish:register:export")
    @Log(title = "鉴定受理登记", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(IdAcceptRegister idAcceptRegister) {
        List<IdAcceptRegister> list = null;
        if (StringUtils.isNotEmpty(idAcceptRegister.getExportIds())) {
            list = idAcceptRegisterService.selectRecordByIds(idAcceptRegister.getExportIds().split(","));
        } else {
            // 条件查询信息
            list = idAcceptRegisterService.selectIdAcceptRegisterList(idAcceptRegister);
        }
        ExcelUtil<IdAcceptRegister> util = new ExcelUtil<IdAcceptRegister>(IdAcceptRegister.class);
        return util.exportExcel(list, "案件数据");
    }


    @Log(title = "案件管理excel导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String year) throws Exception {
        // 文件转字节
        byte[] bytes = file.getBytes();
        InputStream in = new ByteArrayInputStream(bytes);
        ExcelUtil<IdAcceptRegister> util = new ExcelUtil<IdAcceptRegister>(IdAcceptRegister.class);
        List<IdAcceptRegister> dataList = util.importExcel(in);
        String operId = ShiroUtils.getUserId().toString();
        String operName = ShiroUtils.getSysUser().getUserName();
        String message = idAcceptRegisterService.importIdAcceptRegister(dataList, updateSupport, operId, operName, year);
        return AjaxResult.success(message);
    }


    //    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {

        ExcelUtil<IdAcceptRegister> util = new ExcelUtil<IdAcceptRegister>(IdAcceptRegister.class);
        List<IdAcceptRegister> list = new ArrayList<>();
        IdAcceptRegister idAcceptRegister = new IdAcceptRegister();
        //送鉴单位
        idAcceptRegister.setSendUnit("（示范，本行勿删）");
        //来文标题
        idAcceptRegister.setTitle("来文标题(示范)");
        //来文文号
        idAcceptRegister.setDocumentNum("来文文号(示范)");
        //送鉴日期
        idAcceptRegister.setSendDate(new Date());
        //受理日期
        idAcceptRegister.setAcceptDate(new Date());
        //鉴定组长
        idAcceptRegister.setGroupLeader("对应人员的登陆名称(示范)");
        //样本类别
        idAcceptRegister.setCategory("报纸,音像制品,电子出版物");
        //样本种类数量
        idAcceptRegister.setTypes("1");
        //样本数量
        idAcceptRegister.setNum(Long.valueOf("10"));
        list.add(idAcceptRegister);
        return util.importDataTemplateExcel(list, "案件数据");
    }


    /**
     * 新增鉴定受理登记
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
//        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//        for (int i =0 ;i<categoryAll.length;i++) {
//            Map<String,Object> map = new HashMap<String,Object>();
//            map.put("val",categoryAll[i]);
//            map.put("categoryName",categoryAll[i]);
//            map.put("flag",false);
//            list.add(map);
//        }

        String userName = ShiroUtils.getSysUser().getUserName();
        mmap.put("userName", userName);
        //上一个 鉴定组长
        Map<String, Object> map = new HashMap<>();
        map.put("groupId", "notNull");
        IdAcceptRegister gouper = new IdAcceptRegister();
        gouper.setParams(map);
        List<IdAcceptRegister> registers = idAcceptRegisterService.selectIdAcceptRegisterList(gouper);
        if (registers.size() != 0) {
            mmap.put("groupId", registers.get(0).getGroupId());
            mmap.put("groupLeader", registers.get(0).getGroupLeader());
        }
//        mmap.put("listCategory", list);
        return prefix + "/add";
    }

    /**
     * 新增保存鉴定受理登记
     */
//    @RequiresPermissions("publish:register:add")
    @Log(title = "鉴定受理登记", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(IdAcceptRegister idAcceptRegister) {
        idAcceptRegister.setCreateBy(ShiroUtils.getUserId().toString());
        idAcceptRegister.setCreateName(ShiroUtils.getSysUser().getUserName());
        idAcceptRegister.setAuditStatus("3");

        //来函文件后台排序 按照
        if (StringUtils.isNotEmpty(idAcceptRegister.getAcceptFiles())) {
            System.out.println("进入非空判断");
            if (idAcceptRegister.getAcceptFiles().indexOf(",") != -1) {
                System.out.println("进入逗号判断");

                idAcceptRegister.setAcceptFiles(picSort(idAcceptRegister.getAcceptFiles()));
            }
        }

        return toAjax(idAcceptRegisterService.insertIdAcceptRegister(idAcceptRegister));
    }

    /**
     * 修改鉴定受理登记
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(id);
        if (StringUtils.isNotEmpty(idAcceptRegister.getCategory())) {
            String[] categorys = idAcceptRegister.getCategory().split(",");
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < categoryAll.length; i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("val", categoryAll[i]);
                map.put("categoryName", categoryAll[i]);
                map.put("flag", false);
                for (String category : categorys) {
                    if (categoryAll[i].equals(category)) {
                        map.put("flag", true);
                    }
                }
                list.add(map);
            }
            mmap.put("listCategory", list);
            mmap.put("idAcceptRegister", idAcceptRegister);
        }
        return prefix + "/edit";
    }

    /**
     * w
     * 查看鉴定受理登记
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(id);
        if (StringUtils.isNotEmpty(idAcceptRegister.getCategory())) {
            String[] categorys = idAcceptRegister.getCategory().split(",");
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < categoryAll.length; i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("val", categoryAll[i]);
                map.put("categoryName", categoryAll[i]);
                map.put("flag", false);
                for (String category : categorys) {
                    if (categoryAll[i].equals(category)) {
                        map.put("flag", true);
                    }
                }
                list.add(map);
            }
            String userId = String.valueOf(ShiroUtils.getUserId());
            mmap.put("userId", userId);
            mmap.put("listCategory", list);
            mmap.put("idAcceptRegister", idAcceptRegister);
        }
        return prefix + "/detail";
    }

    /**
     * 修改保存鉴定受理登记
     */
//    @RequiresPermissions("publish:register:edit")
    @Log(title = "鉴定受理登记", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(IdAcceptRegister idAcceptRegister) {
        //来函文件后台排序 按照
        if (StringUtils.isNotEmpty(idAcceptRegister.getAcceptFiles())) {
            System.out.println("进入非空判断");
            if (idAcceptRegister.getAcceptFiles().indexOf(",") != -1) {
                System.out.println("进入逗号判断");

                idAcceptRegister.setAcceptFiles(picSort(idAcceptRegister.getAcceptFiles()));
            }
        }
        return toAjax(idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister));
    }

    /**
     * 删除鉴定受理登记
     */
//    @RequiresPermissions("publish:register:remove")
    @Log(title = "鉴定受理登记", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(idAcceptRegisterService.deleteIdAcceptRegisterByIds(ids));
    }

    /**
     * 是否启用状态修改
     */
    @Log(title = "鉴定受理登记", businessType = BusinessType.UPDATE)
//    @RequiresPermissions("publish:register:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(IdAcceptRegister idAcceptRegister) {
        return toAjax(idAcceptRegisterService.changeStatus(idAcceptRegister));
    }

    /**
     * 审核鉴定受理登记
     */
    @GetMapping("/audit")
    public String audit() {
        return prefix + "/audit";
    }


    /**
     * 审核记录 关联按键选择 单选
     */
    @GetMapping("/registerRadio")
    public String checkRadio() {
        return prefix + "/registerRadio";
    }


    /**
     * 创
     */
//    @RequiresPermissions("publish:register:edit")
    @Log(title = "一键更新word文档", businessType = BusinessType.UPDATE)
    @PostMapping("/refresh/{id}")
    @ResponseBody
    public AjaxResult refresh(@PathVariable("id") Long id, ModelMap mmap) {

        return toAjax(idAcceptRegisterService.ApprovalRecordRefreshByRecordId(id));
    }

    @Log(title = "审批", businessType = BusinessType.UPDATE)
    @PostMapping("/handle")
    @ResponseBody
    public AjaxResult handleApproval(IdAcceptRegister idAcceptRegister) {
        return toAjax(idAcceptRegisterService.handleApproval(ShiroUtils.getUserId().toString(), ShiroUtils.getSysUser().getUserName(), idAcceptRegister));
    }

    public String picSort(String URLS) {

        System.out.println("进入 图片排序");
        List<String> urls = Arrays.asList(URLS.split(","));
        List<String> newUrls = new ArrayList<>();
        int i = 0;


        //然后通过比较器来实现排序

        Map<String, String> map = new TreeMap<String, String>();
        for (String url : urls) {
            String[] strs = url.split("/");
            String name = strs[strs.length - 1].split(",")[0];
            map.put(String.valueOf(i), name);
            i++;
        }

        List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());


        //然后通过比较器来实现排序
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            //升序排序
            public int compare(Map.Entry<String, String> o1,
                               Map.Entry<String, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }

        });

        for (Map.Entry<String, String> mapping : list) {
            System.out.println(mapping.getKey() + ":" + mapping.getValue());
            newUrls.add(urls.get(Integer.parseInt(mapping.getKey())));
        }

        return String.join(",", newUrls);
    }

    /**
     * 是否启用状态修改
     */
//    @RequiresPermissions("publish:register:edit")
    @PostMapping("/checkDeliver")
    @ResponseBody
    public AjaxResult checkDeliver(Long id) {
        System.out.println("id="+id);
        if (id!=null){
            IdAcceptRegister idAcceptRegister=idAcceptRegisterService.selectIdAcceptRegisterById(id);
            if (idAcceptRegister!=null&&idAcceptRegister.getId()!=null){
                if ("6".equals(idAcceptRegister.getAuditStatus())){
                    //查询对应的鉴定样本状态
                    IdIdentsample sample=new IdIdentsample();
                    sample.setRegisterId(id);
                    List<IdIdentsample> sampleAll=idIdentsampleService.selectIdIdentsampleList(sample);
                    if (sampleAll.size()==0){
                        return AjaxResult.warn("对应鉴定样本不能为空");
                    }
                    Map<String,Object> map=new HashMap<>();
                    map.put("noCheck","noCheck");
                    sample.setParams(map);
                    List<IdIdentsample>  idIdentsamplesList=idIdentsampleService.selectIdIdentsampleList(sample);
                    if (idIdentsamplesList.size()==0){
                        return AjaxResult.success();

                    }else{
//                        return AjaxResult.warn("还有鉴定样本未鉴定");
                        return AjaxResult.success();
                    }
                }else{
                    return AjaxResult.warn("记录状态未变成完结");
                }



            }else{
                return AjaxResult.error("未找到对应记录");

            }
        }else {
            return AjaxResult.warn("请传入正确参数");

        }
    }
}

